package jsp;

import entity.Emp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月04日9:57
 */
@WebServlet("*.session")
public class SessionServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path=request.getServletPath();
        switch (path){
            case "/add.session":
                addSession(request,response);
                break;
            case "/find.session":
                findSession(request,response);
                break;
            case "/modify.session":
                modifySession(request,response);
                break;
            case "/remove.session":
                removeSession(request,response);
                break;
            case "/clear.session":
                clearSession(request,response);
                break;

        }
    }

    public void addSession(HttpServletRequest request, HttpServletResponse response){
        HttpSession session=request.getSession();
        session.setAttribute("msg","hello session");
        Emp emp=new Emp();
        emp.setId(1);
        emp.setName("alice");
        emp.setSalary(7000.0);
        session.setAttribute("emp",emp);
    }
    public void findSession(HttpServletRequest request, HttpServletResponse response){
        HttpSession session=request.getSession();
        String msg= (String) session.getAttribute("msg");
        System.out.println(msg);
        Emp emp= (Emp) session.getAttribute("emp");
        System.out.println(emp.getId()+"----"+emp.getName()+"----"+emp.getSalary());
    }
    public void modifySession(HttpServletRequest request, HttpServletResponse response){
        HttpSession session=request.getSession();
        // 设置session的生存时间，单位是秒，默认情况下，session的时间是30分钟
        // session.setMaxInactiveInterval(时间)
        // 一般不建议修改生存时间
        // 如果生存时间设置为0，不是表示删除，而是表示永不过期

        session.setAttribute("msg","Hello World");
        Emp emp=new Emp();
        emp.setId(2);
        emp.setName("coco");
        emp.setSalary(10000.0);
        session.setAttribute("emp",emp);
    }
    public void  removeSession(HttpServletRequest request, HttpServletResponse response){
        //方式一：删除指定key的数据
        request.getSession().removeAttribute("msg");
    }

    public void clearSession(HttpServletRequest request, HttpServletResponse response){
        //方式二:清空所有的session，本质上不是清空，而是销毁了原有的session对象，重新创建了一个新的对象
        request.getSession().invalidate();

    }
}
